# zennotac-backend/app/routes/log_receiver.py

from fastapi import APIRouter, Request
from pydantic import BaseModel
from datetime import datetime

from app.exceptions.handlers import format_error
from fastapi.responses import JSONResponse
from typing import Optional

from app.config.base_setting import frontend_logger, backend_logger


router = APIRouter()

class FrontendLog(BaseModel):
    timestamp: str
    level: str
    message: str
    stack: Optional[str] = None
    context: Optional[str] = None
    url: Optional[str] = None
    user_agent: Optional[str] = None

@router.post("/log")
async def receive_log(log: FrontendLog, request: Request):
    log_entry = (
        f"Time: {datetime.now().isoformat()} | "
        f"Level: {log.level.upper()} | "
        f"Message: {log.message} | "
        f"Stack: {log.stack or ''} | "
        f"Context: {log.context or ''} | "
        f"URL: {log.url or str(request.url)} | "
        f"User-Agent: {log.user_agent or request.headers.get('user-agent', '')}"
    )

    try:
        level = log.level.lower()
        if level == "error":
            frontend_logger.error(log_entry)
        elif level == "warning" or level == "warn":
            frontend_logger.warning(log_entry)
        else:
            frontend_logger.info(log_entry)
        return {"status": "ok"}
    except Exception as e:
        backend_logger.exception("Failed to log frontend message")
        return JSONResponse(
            status_code=500,
            content=format_error(code=500, message="Log handling failed", trace=str(e))
        )
    

from fastapi import APIRouter, Request
from pydantic import BaseModel
from typing import Optional
from datetime import datetime
import logging

router = APIRouter()

class FrontendLog(BaseModel):
    timestamp: str
    level: str
    message: str
    stack: Optional[str] = None
    context: Optional[str] = None
    url: Optional[str] = None
    user_agent: Optional[str] = None

@router.post("/log")
async def receive_log(log: FrontendLog):
    log_line = f"[{log.timestamp}][{log.level.upper()}] {log.message} | {log.context or ''} | {log.url}"
    logging.getLogger("frontend").log(
        level=getattr(logging, log.level.upper(), logging.ERROR),
        msg=log_line + f"\n{log.stack or ''}"
    )
    return {"status": "ok"}
